from datetime import datetime

from django.contrib import messages

from commonTool.class_convert_tool import ClassConvertTool
from commonTool.logs.logs_wrapper import LogUtil
from page.application.const import SESSION_USER_KEY
from page.application.models import User

logs = LogUtil()


class LoginApi:

    @logs
    def login(self, request, username, password):
        if self.isExist(username):
            user = User.objects.get(username=username, del_flag=0)
            if user.password == password:
                # 登录成功
                user_json_str = ClassConvertTool.convertJson(user)
                if user_json_str:
                    request.session[SESSION_USER_KEY] = user_json_str
                    logs.info("[ 用户登录 ] 登录成功 缓存SESSION = ", request.session.get(SESSION_USER_KEY))

                    return user_json_str
                else:
                    logs.warning("[ 用户登录 ] 登录响应VO异常:", user_json_str)
                    messages.error(request, '登录异常')
            else:
                # 登录失败
                logs.warning(f"[ 用户登录 ] 用户{username} 密码错误")
                messages.error(request, '密码错误')
        else:
            logs.warning(f"[ 用户登录 ] 用户不存在,data:", username, password)
            messages.error(request, '用户不存在')
        return None

    @staticmethod
    def isExist(username):
        user_exists = User.objects.filter(username=username, del_flag=0).exists()
        return user_exists
